﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using ShopOnline.BLL;
using System.IO;

namespace ShopOnline
{
    public partial class ThankYou : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && !string.IsNullOrEmpty(Request.QueryString["key"]))
            {
                int id = int.Parse(Request.QueryString["key"]);

                POSSystem.BLL.CustomerOrders order = new POSSystem.BLL.CustomerOrders();
                order.LoadByPrimaryKey(id);
                if (order.StatusID == OrderStatus.Temporary)
                {
                    order.StatusID = OrderStatus.Pending;
                    order.Save();
                }

                POSSystem.BLL.OrderItems orderItems = POSSystem.BLL.OrderItems.GetOrderItems(order.ID);
                for (int i = 0; i < orderItems.RowCount; i++)
                {
                    if (orderItems.Category == OrderItemCategory.BusinessCard)
                    {
                        BusinessCards c = new BusinessCards();
                        c.LoadByPrimaryKey(orderItems.ProductID);
                        if (c.RowCount > 0)
                        {
                            c.Status = BusinessCardStatus.Submitted;
                            if (View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0)
                                c.CreatedByCustomer = View_Customers.GetCurrentUser().ID;
                            c.Save();
                        }
                    }
                    orderItems.MoveNext();
                }

                try
                {
                    string tempFile = Server.MapPath("~/MailTemplates/NewOrder.htm");
                    string content = File.ReadAllText(tempFile);
                    content = string.Format(content, order.s_CustomerName, order.s_ShipAddress, order.s_CustomerPhone);
                    string recipients = POSSystem.BLL.Utilities.GetConfigAppSetting("AutoMailRecipients");
                    POSSystem.BLL.Utilities.SendEmail(recipients, "New Customer Order", content);
                }
                catch (Exception ex)
                {
                    ErrorLog.WriteToFile("New Customer Order", ex.Message, ex.StackTrace);
                }
            }
        }
    }
}